class ProductsController < ApplicationController
  before_action :set_product, only: [:show, :edit, :update, :destroy]
  before_action :set_warehouse
  
  respond_to :html

  def index
    @products = Product.where(build_search(search_params)).order(created_at: :desc).page(params[:page])

    respond_to do |format|
      format.html{}
      format.json {render json:@products }
    end
    
  end

  def show
    respond_with(@product)
  end

  def new
    @product = Product.new
  end

  def edit
  end

  def create
    @product = Product.new(product_params)
    @product.save
    respond_with(@product)
  end

  def update
    @product.update(product_params)
    respond_with(@product)
  end

  def destroy
    @product.destroy
    respond_with(@product)
  end

  private
    def set_product
      @product = Product.find(params[:id])
    end

    def product_params
      params.require(:product).permit(:pn, :name, :desc, :unit,:warehouse_id,:quantity)
    end
    
    def set_warehouse 
      @warehouse = Warehouse.find(params[:warehouse_id]) if params[:warehouse_id].present?
    end 
    
    def set_page_title
      @page_title = "物料管理" 
    end
    
    def search_params     
        if params[:product].present?  
          product_params.permit(:pn, :name, :desc,)
        end                     
    end
end
